<?php

class Cdn_domain extends CI_Model {

	function __construct() {
		parent::__construct();
	}

	function filter($data) {
		$msg = array();
		if (!is_array($data) OR empty($data)) $msg[] = "输入数据错误";
		if (!array_key_exists('stat_mode', $data)) $msg[] = "统计模式错误";
		if (!array_key_exists('fee_mode', $data)) $msg[] = "计费方法错误";
		if (!array_key_exists('charge_mode', $data)) $msg[] = "计费类型错误";
		if (!array_key_exists('cache_mode', $data)) $msg[] = "缓存方式错误";
		if (!array_key_exists('log_mode', $data)) $msg[] = "日志方式错误";
		if (!array_key_exists('analysis_mode', $data)) $msg[] = "分析模式错误";
		if (!array_key_exists('domain', $data)) $msg[] = "域名不能为空";
		
		foreach ($data as $k => $v) {
			switch($k) {
			case 'stat_mode':
				if (!in_array(intval($v), array(1,2,3))) $msg[] = "统计模式数据非法";
				break;
			case 'fee_mode':
				if (!in_array(intval($v), array(1,2,3,4))) $msg[] = "计费方法数据非法";
				break;
			case 'charge_mode':
				if (!in_array(intval($v), array(1,2))) $msg[] = "计费类型数据非法";
				break;
			case 'cache_mode':
				if (!in_array(intval($v), array(1,2,3,4))) $msg[] = "缓存方式数据非法";
				break;
			case 'log_mode':
				if (!in_array(intval($v), array(1,2,3))) $msg[] = "日志方式数据非法";
				break;
			case 'analysis_mode':
				if (!in_array(intval($v), array(1,2,3))) $msg[] = "分析模式数据非法";
				break;
			case 'domain':
				if ($v == '') {
					$msg[] = "域名数据错误";
				}
				break;
			}
		}
		$status = FALSE;
		if (empty($msg)) {
			$status = TRUE;
		}
		return array('status' => $status, 'msg' => $msg);
	}

	function add($data) {
		$domain = explode("\n", $data['domain']);
		if (count($domain) == 0) return;
		$ids = array();
		foreach ($domain as $v) {
			if (!$this->exist($v)) {
				$cond['status'] = 1;
				$cond['created_at'] = date('Y-m-d h:i:s', mktime());
				$cond['updated_at'] = date('Y-m-d h:i:s', mktime());
				if (trim($v) == '') continue;
				$cond['domain'] = $v;
				$cond['stat_mode'] = $data['stat_mode'];
				$cond['fee_mode'] = $data['fee_mode'];
				$cond['log_mode'] = $data['log_mode'];
				$cond['analysis_mode'] = $data['analysis_mode'];
				$cond['cache_mode'] = $data['cache_mode'];
				$cond['charge_mode'] = $data['charge_mode'];
				$this->db->insert('domain', $cond);
				$ids[] = $this->db->insert_id();
			}
		} 
		return $ids;
	}

	function exist($domain) {
		$cond = array('domain' => $domain, 'status' => 1);
		$this->db->where($cond);
		$query = $this->db->get('domain');
		if ($query->num_rows() >= 1) return TRUE;
		return FALSE;	
	}

	function get_unbind_domain() {
		$cond = array('bind_flag' => 0, 'status' => 1);
		$this->db->where($cond);
		$query = $this->db->get('domain');
		return $query->result_array();
	}

	function del($id) {
		$data = array('status' => 0);
		$data['updated_at'] = date('Y-m-d h:i:s', mktime());
		$this->db->where('id', $id);
		$this->db->update('domain', $data); 
	}

	function find($id) {
		$this->db->where('id', $id); 
		$query = $this->db->get('domain');
		return $query->result_array();
	}
}
